<template>
  <a-drawer
    :title="title"
    width="90%"
    :visible="visible"
    :confirmLoading="loading"
    @close="
      () => {
        this.visible = false
        this.a = false
      }
    "
  >
    <a-spin :spinning="loading">
      <a-form-model ref="form" :model="entity" :rules="rules" v-bind="layout">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="采购订单名称" prop="Name">
              <a-input :disabled="disabled" v-model="entity.Name" autocomplete="off" />
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="供货单位" prop="SupplierId">
              <sup-select v-model="entity.SupplierId" :disabled="disabled"></sup-select>
              <!-- <a-input v-model="entity.OutsourcingCompanyId" autocomplete="off" /> -->
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="订单类型" prop="Type">
              <a-select v-model="entity.Type" >
                <a-select-option
                  v-for="(item, index) in TypeList"
                  :value="item.DicValue"
                  :key="index"
                >{{ item.DicName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="8">
            <a-form-model-item label="制单人" prop="Remarks">
              {{ userName }}

            </a-form-model-item>
          </a-col> -->
        </a-row>

        <a-row>
          <a-col :span="8">
            <a-form-model-item label="采购日期" prop="PurchaseDate">
              <a-date-picker
                :disabled="disabled"
                valueFormat="YYYY-MM-DD"
                style="width: 100%"
                @change="datechange"
                v-model="entity.PurchaseDate"
              />
              <!-- :disabled-date="disabledDate" -->
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="预计交货日期" prop="HandoverDate">
              <a-date-picker
                :disabled="disabled"
                valueFormat="YYYY-MM-DD"
                style="width: 100%"
                :disabled-date="disabledDate"
                v-model="entity.HandoverDate"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="合同编号" prop="ContractCode">
              <a-input :disabled="disabled" v-model="entity.ContractCode" autocomplete="off" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="备注" prop="Remarks">
              <a-textarea v-model="entity.Remarks" autocomplete="off" :disabled="disabled" />
              <!-- <a-input :disabled="disabled" v-model="entity.Remark" autocomplete="off" /> -->
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="合同附件">
              <!--              Authorization = 'Bearer ' + TokenCache.getToken()-->
              <a-upload
                name="file"
                :multiple="true"
                :action="`${$rootUrl}/PB/pb_purchase/UploadFileByForm`"
                :fileList="fileList"
                @change="handleChange"
                :disabled="disabled"
                :headers="{
                  Authorization:'Bearer ' + TokenCache.getToken()
                }"
                @preview="preview"
                listType="picture"
                class="upload-list-inline"
              >
                <a-button :disabled="disabled"> <a-icon type="upload" /> 上传附件 </a-button>
              </a-upload>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>

    <div style="position: relative;">
      <a-button
        v-if="title !== '审核' && title !== '查看' && title !== '确认'"
        type="primary"
        @click="addtable"
        style="margin-right: 10px;position: absolute;right: 0;top: 13px;z-index: 999;"
      >
        添加物品
      </a-button>
      <a-tabs default-active-key="1">
        <a-tab-pane key="1" tab="物品明细">
          <a-table
            @change="handleTableChange"
            :columns="columns"
            :data-source="dataArr"
            :loading="loading"
            :pagination="false"
            :rowKey="(row, index) => row.I_id || row.Id"
            size="small"
            bordered
          >
            <template slot="Nums" slot-scope="text, record">
              <a-input
                size="small"
                class="input"
                :disabled="disabledNums"
                type="number"
                v-model="record.Nums"
                @change="RecNumchange($event, record)"
                style="text-align: right;"
              ></a-input>
            </template>

            <template slot="Price" slot-scope="text, record">
              <a-input
                size="small"
                class="input"
                :disabled="disabledNums"
                type="number"
                v-model="record.Price"
                :min="0"
                @change="pricechange(record)"
                style="text-align: right;"
              ></a-input>
            </template>
            <template slot="Rate" slot-scope="text, record">
              <!--              <enum-select code="TaxRate" v-model="record.Rate" :disabled="disabledNums"></enum-select>-->
              <a-select v-model="record.Rate" style="width: 100px;">
                <a-select-option
                  v-for="(item, index) in RateList"
                  :value="item.DicValue"
                  :key="index"
                >{{ item.DicName }}
                </a-select-option>
              </a-select>
              <!-- <a-input
                size="small"
                class="input"
                :disabled="disabled"
                type="number"
                v-model="record.Price"
                style="text-align: right;"
              ></a-input> -->
            </template>
            <template slot="operation" slot-scope="text, record, index">
              <div class="Deleted-row-operations">
                <a @click.stop="cancel(index, [record.I_id], [record])" v-if="!disabledNums">
                  <a>删除</a>
                </a>
              </div>
            </template>
            <template slot="dataIndex" slot-scope="text, record, index">
              <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
            </template>
            <template slot="Amount" slot-scope="text, record">
              <span>{{ AmountNum(record) }}</span>
            </template>
            <template slot="TotalWeight" slot-scope="text, record">
              <span>{{ TotalWeightNum(record) }}</span>
            </template>
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </div>

    <div style="margin-top: 50px"></div>
    <MaterialChoose ref="materialChoose" @onChoose="handleChoose"></MaterialChoose>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1
      }"
    >
      <!-- <a-button
        v-if="title !== '审核' && title !== '查看' && title !== '确认'"
        type="primary"
        @click="addtable"
        style="margin-right: 10px"
      >
        添加物品
      </a-button> -->
      <a-button
        :style="{ marginRight: '8px' }"
        @click="
          () => {
            this.visible = false
            this.a = false
          }
        "
      >取消</a-button
      >
      <a-button
        @click="handleAudit(entity.Id, 'Approve')"
        type="primary"
        :style="{ marginRight: '8px' }"
        v-if="title === '审核'"
      >
        通过
      </a-button>
      <a-button
        v-if="title !== '审核' && title !== '查看' && title !== '确认'"
        type="primary"
        @click="handleSubmit"
        :loading="loading"
      >保存</a-button
      >
      <a-button v-if="title == '确认'" type="primary" @click="signfor">确认</a-button>
    </div>
  </a-drawer>
</template>
<script>
// import EnumSelect from '@/components/BaseEnum/BaseEnumSelect'
import SupSelect from './SupplierSelectClone.vue'
// import MaterialChoose from '@/components/Material/MaterialChooseCopy1.vue'
import MaterialChoose from './MaterialChoose'
import TokenCache from '@/utils/cache/TokenCache'
import moment from 'moment'
export default {
  props: {
    parentObj: Object
  },
  components: {
    MaterialChoose,
    SupSelect
    // EnumSelect
  },
  computed: {},
  data () {
    return {
      TokenCache,
      RateList: [],
      fileList: [],
      TypeList: [],
      userName: '',
      ParentIdTreeData: [],
      dataArr: [],
      a: true,
      disabled: false,
      disabledNums: false,
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          scopedSlots: { customRender: 'dataIndex' },
          width: '50px'
        },
        { title: '编号', dataIndex: 'Code', ellipsis: true },

        { title: '名称', dataIndex: 'Name' }, // scopedSlots: { customRender: 'MaterialName' }
        {
          title: '规格',
          dataIndex: 'Spec'
          // ellipsis: true

          // scopedSlots: { customRender: 'WorkshopName' }
        },
        {
          title: '采购单位',
          dataIndex: 'PurchaseName',

          ellipsis: true
        },
        // { title: '型号', dataIndex: 'Weight1', ellipsis: true }, // scopedSlots: { customRender: 'Weight' }
        { title: '数量', dataIndex: 'Nums', ellipsis: true, scopedSlots: { customRender: 'Nums' }, align: 'right', customRender: this.$NumFormatting },

        { title: '单价', dataIndex: 'Price', align: 'right', scopedSlots: { customRender: 'Price' }, customRender: this.$NumFormatting },
        { title: '金额', dataIndex: 'Amount', align: 'right', ellipsis: true, scopedSlots: { customRender: 'Amount' }, customRender: this.$NumFormatting },
        { title: '税率%', dataIndex: 'Rate', align: 'right', ellipsis: true, scopedSlots: { customRender: 'Rate' } },
        {
          title: '保质期单位',
          dataIndex: 'PeriodOfValidityUnit'
        },
        {
          title: '保质期',
          dataIndex: 'PeriodOfValidity',
          align: 'right'
        },

        {
          title: '操作',
          dataIndex: 'operation',
          width: '10%',
          align: 'center',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      rules: {
        Type: [{ required: true, message: '未输入', trigger: 'blur' }],
        Name: [{ required: true, message: '未输入', trigger: 'blur' }],
        Rate: [{ required: true, message: '未输入', trigger: 'blur' }],
        TotalAmount: [{ required: true, message: '未输入', trigger: 'blur' }],
        TotalWeight: [{ required: true, message: '未输入', trigger: 'blur' }],
        PurchaseDate: [{ required: true, message: '请输入外采日期', trigger: 'change' }],
        // HandoverDate: [{ required: true, message: '请输入外采日期', trigger: 'change' }],
        // OutsourcingCompanyId: [{ required: true, message: '未输入', trigger: 'change' }],
        SupplierId: [{ required: true, validator: this.validatePass1, trigger: 'blur' }],
        StorId: [{ required: true, message: '未输入', trigger: 'change' }]
      },
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      visible: false,
      loading: false,
      entity: {},
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面啊可以通过下拉框进行选择
        showSizeChanger: true,
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize)
      },
      title: '',
      id: ''
    }
  },
  // watch: {
  //   dataArr: {
  //     deep: true,
  //     handler(a, b) {
  //       console.log(a)
  //       let TotalWeight = 0
  //       var TotalAmount = 0

  //       a.forEach(item => {
  //         TotalWeight = (Number(item.TotalWeight) + Number(TotalWeight)).toFixed(2)
  //         TotalAmount = (Number(item.Amount) + Number(TotalAmount)).toFixed(2)
  //       })
  //       console.log(TotalAmount, '单价', TotalWeight, '重量')
  //       this.$set(this.entity, 'TotalAmount', TotalAmount)
  //       this.$set(this.entity, 'TotalWeight', TotalWeight)
  //     }
  //   }
  // },
  methods: {
    pricechange (row) {
      console.log(row.Price)
      if (Number(row.Price) < 0) {
        this.$message.error('单价不能小于0')
        this.$set(row, 'Price', 0)
      }
    },
    preview (file) {
      console.log(file)

      var url = file.url || file.response.url
      window.open(url)
      // this.fileList = file.fileList
    },
    handleChange (file, fileList, event) {
      this.fileList = file.fileList
      this.entity.Files = this.fileList.filter(x => x.status === 'done').map(x => x.url || x.response.url)
      // 上传
    },
    RecNumchange (eve, row) {
      if (row.Nums.split('.').length > 1) {
        this.$message.error('不能填写小数点')
        row.Nums = Math.floor(Number(row.Nums))
      }
    },
    signfor () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$http.post(`/PB/PB_Purchase/DeterminePurchaseData?PurchaseId=${this.id}`, {}).then(resJson => {
            if (resJson.Success) {
              this.$message.success('确认成功!')
              this.visible = false
              this.parentObj.getDataList()
            } else {
              this.$message.error(resJson.Msg)
            }
          })
          // this.$http.post(`/PB/PB_Purchase/UpdatePurchaseData?PurchaseId=${this.id}&StorId=${this.entity.StorId}`, {}).then(resJson => {
          //   if (resJson.Success) {
          //     this.$message.success('确认成功!')
          //     this.visible = false
          //     this.parentObj.getDataList()
          //   } else {
          //     this.$message.error(resJson.Msg)
          //   }
          // })
        } else {
          this.$message.error('请添加收货仓库')
        }
      })
    },
    SelectOrgan () {
      this.$http.post('/PB/PB_PackList/GetDetpList', {}).then(resJson => {
        if (resJson.Success) {
          this.ParentIdTreeData = resJson.Data
        }
      })
    },
    getsub () {
      this.loading = true

      this.entity.ContractDate = moment(this.entity['ContractDate'])
      this.entity.PurchaseDate = moment(this.entity['PurchaseDate'])

      this.entity.HandoverDate = this.entity.HandoverDate ? moment(this.entity['HandoverDate']) : null
      var arr = JSON.parse(JSON.stringify(this.dataArr))
      arr.forEach(item => {
        item.Rate = item.Rate ? item.Rate : 0
      })
      this.entity.PurchaseDetail = [...arr]
      console.log(this.entity)

      this.$http.post('/PB/PB_Purchase/SavePurchaseData', this.entity).then(res => {
        this.loading = false
        if (res.Success) {
          this.$message.success('操作成功!')
          this.visible = false
          this.a = false
          this.parentObj.getDataList()
        } else {
          this.$message.error(res.Msg)
        }
      })
    },
    TotalWeightNum (record) {
      if (record.Nums && record.Weight) {
        record.TotalWeight = (Number(record.Weight) * Number(record.Nums)).toFixed(4)
      } else {
        record.TotalWeight = 0
      }
      return record.TotalWeight
    },
    AmountNum (record) {
      if (record.Price && record.Nums) {
        record.Amount = (Number(record.Price) * Number(record.Nums)).toFixed(4)
      } else {
        record.Amount = 0
      }
      return record.Amount
    },
    datechange (a) {
      console.log(a)
      this.$set(this.entity, 'HandoverDate', null)
    },
    validatePass1 (rule, value, callback) {
      console.log(rule, value)
      if (this.entity.SupplierId) callback()
      else callback(new Error('请输入'))
    },
    // onChange(checked) {
    //   // console.log(`a-switch to ${checked}`)
    //   this.checked = checked
    //   console.log(this.checked)
    // },
    // 子表明细删除
    cancel (index, ids, rows) {
      console.log(index)
      let deleteIdArr = []
      // 给每一行设置选中值用于后续判断逻辑
      rows.forEach((item) => (item['checked'] = true))
      // 过滤有id的列表用于提交请求id数组
      const newDetaiData = rows.filter((item) => item.Id)
      if (newDetaiData.length > 0) {
        // 说明有id
        deleteIdArr = newDetaiData.map((item) => {
          return item.Id
        })
      }
      if (this.title === '编辑') {
        // 判断如果是当前行删除  直接删除
        if (ids === undefined) return this.dataArr.splice(index, 1)
        // 判断要删除的数组中是否存在返回的id列表 再弹窗 否则直接删除即可
        const isBool = rows.some((item) => item.Id)
        if (isBool) {
          this.$confirm('确认删除吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            return new Promise((resolve, reject) => {
              this.$http.post('/pb/pb_purchasedetail/DeleteData', deleteIdArr).then((res) => {
                if (res.Success) {
                  this.loading = false
                  // 对比处理id  过滤出没有符合条件的重新赋值子表
                  this.dataArr.forEach(item => {
                    deleteIdArr.forEach(v => {
                      if (item.Id === v) {
                        item.checked = true
                      }
                    })
                  })
                  // 过滤出没有选中删除的数组重新赋值 为已删除列表
                  const resultArr = this.dataArr.filter((item) => !item.checked)
                  this.dataArr = resultArr
                  // 删除选中列表初始化
                  this.selectedRowKeys = []
                  this.$message.success('删除成功')
                } else {
                  this.loading = false
                  // 删除选中列表初始化
                  this.selectedRowKeys = []
                  this.$message.error(res.Msg)
                }
              })
            }).catch(() => console.log('Oops errors!'))
          })
        } else {
          const resultArr = this.dataArr.filter((item) => !item.checked)
          this.dataArr = resultArr
          // 删除选中列表初始化
          this.selectedRowKeys = []
        }
      }
    },
    Statechange () {
      this.data = []
      this.OutsourcingBillDetail = []
      console.log(8888888888)
    },
    handleChoose (a) {
      // 添加后数组

      console.log(a)
      a.forEach(item => {
        this.$set(item, 'MaterialId', item.Id)
        this.$set(item, 'Price', 0)
        this.$set(item, 'Amount', 0)
        this.$set(item, 'Id', '')
      })
      a = [...this.dataArr, ...a]
      var newobj = {}
      // reduce 方法
      var maparr = []
      a = a.reduce((preVal, curVal) => {
        if (!newobj[curVal.Code]) {
          // 如果这个对象里面没有对应的ID 就push进新数组 并给此ID赋值下次判断有这个ID就说明是重复
          preVal.push(curVal)
          newobj[curVal.Code] = curVal.Code
        } else {
          // 如果有对应的ID就说明重复 数组里面有重复对象的MaterialId,添加到另外一个数组是重复的对象
          maparr.push(curVal)
        }
        return preVal
      }, [])
      if (maparr.length > 0) {
        this.$message.error('重复物品已筛选掉')
      }

      console.log(a, maparr)
      this.dataArr = [...a]
    },
    // 添加物品
    addtable () {
      this.$refs.materialChoose.openChoose()
    },
    disabledDate (current) {
      // console.log(current);
      const startValue = this.entity.PurchaseDate
      if (startValue) {
        return startValue.valueOf() >= current.valueOf()
      } else {
        return current.valueOf() <= moment().subtract(1, 'days')
      }
    },
    init () {
      this.visible = true

      this.dataArr = []

      // this.entity.Amount = (this.entity.Price * this.a).toFixed(2)
      // this.entity = { Id: '', Status: 0, OutsourcingDate: moment(), ExpectedDate: moment() }
      this.entity = {}
      this.a = true
      this.fileList = []
      this.TypeList = []
      this.$http.post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', { Condition: 'DicKey', Keyword: 'PurchaseType' }).then(resJson => {
        this.loading = false
        this.TypeList = resJson.Data.DictionaryDetailsList
      })
      this.RateList = []
      this.$http.post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', { Condition: 'DicKey', Keyword: 'TaxRate' }).then(resJson => {
        this.loading = false
        this.RateList = resJson.Data.DictionaryDetailsList
      })
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    OutsourcingCompanyId () {
      this.flag = null
      console.log(111)
    },
    // 审核
    handleAudit (id, type) {
      this.loading = true
      this.$http.post('/PB/pb_purchase/ToExaminePurchaseData?PurchaseId=' + id, {}).then(resJson => {
        this.loading = false
        if (resJson.Success) {
          this.$message.success('操作成功!')
          this.visible = false
          this.parentObj.getDataList()
        } else {
          this.$message.error(resJson.Msg)
        }
      })
    },
    getFileName (url) {
      const reg = /^.*\/(.*?)$/
      const match = reg.test(url)
      if (match) {
        return RegExp.$1
      } else {
        return ''
      }
    },
    openForm (id, title) {
      this.init()
      this.title = title
      if (title === '查看' || title === '审核' || title === '确认' || title === '编辑') {
        this.disabled = true
        this.disabledNums = true
        if (title === '编辑') {
          this.disabledNums = false
          this.disabled = false
        }
      } else {
        this.disabled = false
        this.disabledNums = false
      }
      console.log(title)
      if (title === '确认') {
        this.SelectOrgan()
      }
      if (id) {
        this.id = id
        this.loading = true
        this.$http.post('/PB/pb_purchase/GetPurchaseData?PurchaseId=' + id, {}).then(res => {
          this.loading = false
          if (res.Success) {
            console.log(res)
            res.Data.PurchaseDetail.forEach(item => {
              item.Name = item.MaterialName
              item.Spec = item.MaterialSpec
              item.Code = item.MaterialCode
              item.PurchaseName = item.UnitGroupName
            })

            res.Data.PurchaseDate = moment(res.Data.PurchaseDate)
            res.Data.ContractDate = moment(res.Data.ContractDate)

            res.Data.HandoverDate = res.Data.HandoverDate ? moment(res.Data.HandoverDate) : null
            this.entity = res.Data
            this.entity.Files.forEach((item, index) => {
              this.fileList.push({
                name: this.getFileName(item),
                uid: index,
                status: 'done',
                url: item
              })
            })
            // this.fileList = this.entity.Files.map((x, index) => {
            //   return { name: this.getFileName(x), uid: index, status: 'done', url: x }
            // })
            this.userName = res.Data.CreatorRealName
            res.Data.PurchaseDetail.forEach(item => {
              if (item.Rate === 0) {
                item.Rate = ''
              } else {
                item.Rate = item.Rate + ''
              }
            })
            this.dataArr = res.Data.PurchaseDetail
            if (this.entity.Status === 4) {
              this.SelectOrgan()
            }
          }
        })
      } else {
        this.userName = localStorage.getItem('userName')
      }
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.sorter = { ...sorter }
    },
    handleSubmit () {
      console.log(this.entity)
      console.log(this.fileList)
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        if (this.dataArr.length === 0) {
          this.$message.error('请添加物品')
          return
        }

        var arr = []
        this.dataArr.forEach(item => {
          if (!item.Nums || Number(item.Nums) <= 0 || item.Price === '') {
            arr.push(item)
          }
        })
        // console.log(arr)
        if (arr.length > 0) {
          this.$message.error('物品中有数量或单价异常请核对')
          return
        }

        this.getsub()
      })
    }
  }
}
</script>

<style scoped>
.productionTask {
  font-size: 14px;
  margin-right: 5px;
  line-height: 39.9999px;
  color: #000000d9;
}
.input {
  text-align: right;
}
.upload-list-inline {
  display: block;
  /* display: flex; */
}
.upload-list-inline >>> .ant-upload-list-item {
  width: 100px;
  float: left;
}
.upload-list-inline >>> .ant-upload-list-item-name {
  white-space: nowrap;

  text-overflow: ellipsis;

  -o-text-overflow: ellipsis;
}
.upload-list-inline >>> .ant-upload-list-item {
  margin-top: 0px;
}
/* .upload-list-inline >>> .ant-upload-list {
  display: flex;
} */
</style>
